﻿#include "ssAsioThread.h"

namespace StarSeeker
{

	ssAsioThread::ssAsioThread()
		:m_service(1), m_work(asio::make_work_guard(m_service)), m_thread(std::bind(&ssAsioThread::RunService, this))
	{
		m_sendEventCount = 0;
		m_sendQueueCount = 0;
	}

	ssAsioThread::~ssAsioThread()
	{
	}

	void ssAsioThread::RunService()
	{
		m_service.run();
	}

	StarSeeker::u32 ssAsioThread::GetSessionCount()
	{
		return (u32)m_sessionMap.size();
	}

	void ssAsioThread::ClearSession()
	{
		std::map<u32, ssAsioSessionPtr>::iterator itr;
		for (itr = m_sessionMap.begin(); itr != m_sessionMap.end(); ++itr)
		{
			asio::error_code ec1, ec2;
			itr->second->GetSocket()->shutdown(asio::ip::tcp::socket::shutdown_both, ec1);
			itr->second->GetSocket()->close(ec2);
			//delete itr->second;
		}
		m_sessionMap.clear();
	}

	void ssAsioThread::SetThreadName(u32 index, const char* name, const wchar_t* wname)
	{
		std::string n1(name);
		n1 += std::to_string(index);
		std::wstring n2(wname);
		n2 += std::to_wstring(index);
		SS_SHARED_PTR<asio::steady_timer> t(new asio::steady_timer(m_service, std::chrono::seconds(5)));
		t->async_wait(std::bind(&ssAsioThread::HandleSetThreadName, this, std::placeholders::_1, t, n1, n2));
	}

	ssAsioSessionPtr ssAsioThread::FindSession(u32 id)
	{
		ssAsioSessionPtr ret;
		std::map<u32, ssAsioSessionPtr>::iterator itr = m_sessionMap.find(id);
		if (itr != m_sessionMap.end())
		{
			ret = itr->second;
		}
		return ret;
	}

	void ssAsioThread::HandleSetThreadName(const asio::error_code& error, SS_SHARED_PTR<asio::steady_timer>& timer, const std::string& name, const std::wstring& wname)
	{
		if (!error)
		{
#ifdef _WIN32
			SetThreadDescription(m_thread.native_handle(), wname.c_str());
#else
			pthread_setname_np(m_thread.native_handle(), name.c_str());
#endif
		}
	}

}
